package com.zdzx.websocket;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;


@Component
public class CloudHandleInterceptor implements HandshakeInterceptor{

	
	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		ServletServerHttpResponse rq=(ServletServerHttpResponse)response;
		//req.getServletResponse().setHeader(name, value);
		// TODO Auto-generated method stub
		ServletServerHttpRequest req=(ServletServerHttpRequest)request;
		//System.out.println(req.getServletRequest().getHeader("Sec-WebSocket-Protocol"));
		rq.getServletResponse().setHeader("Sec-WebSocket-Protocol", req.getServletRequest().getHeader("Sec-WebSocket-Protocol"));
		System.out.println("建立连接之前");
		String path = request.getURI().getPath();
		String[] split = StringUtils.split(path,"/");
		if(split.length!=3) {
			return false;
		}
		attributes.put("uid",split[2]);
		return true;
	}

	
	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Exception exception) {
		// TODO Auto-generated method stub
		
	}

}
